<?php


namespace Modules\Chinadmin\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Auth;

/**
 * 账号模型
 * Class AccountModel
 * @package Modules\Chinadmin\Models
 */
class AccountModel extends Authenticatable
{
    public $table = 'ca_account';
    public $primaryKey = 'id';
    protected $fillable = [
        'name',
        'status'
    ];

    protected $hidden = [
        'created_at',
        'updated_at',
    ];

    //加这个可以让时间成为正常格式。
    protected function serializeDate(\DateTimeInterface $date){
        return $date->format('Y-m-d H:i:s');
    }

    /**
     * 关联公司表
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function company(){
        return $this->belongsTo(CompanyModel::class,'company_id','company_id')->select(['company_id','company_name']);
    }

    /**
     * 关联角色
     */
    public function role(){
        return $this->hasOne(RoleModel::class,'id','role_id')->select();
    }

    /**
     * @param string $guard
     * @return mixed
     */
    public static function getUserInfoByToken($token){

        $user = self::query()->where('api_token',$token)->first();
        return $user;

    }

    /**
     * @param string $guard
     * @return mixed
     */
    public static function getUserInfo($guard = 'dispatch'){

        $uid = Auth::guard($guard)->id();

        if(empty($uid)){
            return mdsResponse(400,"token不正确");
        }

        $user = self::query()->with('company')->find($uid);

        return $user;

    }


    /**
     * 获取用户
     * @param $where
     * @return mixed
     */
    public static function getUser($where,$registration_id = '',$plate_no = ''){

        $filter = [];
        if(!is_array($where)){
            $filter['id'] = $where;
        }else{
            $filter = array_merge($filter,$where);
        }
        $account_info = self::where($filter)->with('company')->first();

        if(empty($account_info)){
            $filter['username'] = $filter['phone'];
            unset($filter['phone']);
            $account_info = self::where($filter)->with('company')->first();
        }
        //d($account_info);

        if(($account_info['registration_id'] != $registration_id) && $registration_id != ''){
            $re = self::where($filter)->update(['registration_id' => $registration_id]);
        }

        if(($account_info['plate_no'] != $plate_no) && $plate_no != ''){
            $re = self::where($filter)->update(['plate_no' => $plate_no]);

            EmployeeModel::where("employee_id",$account_info['employee_id'])->update([
                'app_status' => 1,
                'plate_no' => $plate_no
            ]);
        }

        $account_info = self::where($filter)->with('company')->first();

        return $account_info;

    }




}
